package com.yundasys.lab06ratelimitannotation.annotation;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * @PACKAGE_NAME: com.yundasys.lab06ratelimitannotation.annotation
 * @NAME: AccessLimiterAspect
 * @USER: jiangta
 * @DATE: 2021/1/21
 * @TIME: 10:09 下午
 * @PROJECT_NAME: springboot-labs
 */
@Slf4j
@Component
@Aspect
public class AccessLimiterAspect {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedisScript<Boolean> rateLimitLua;

    @Pointcut("@annotation(com.yundasys.lab06ratelimitannotation.annotation.AccessLimiter)")
    public void cut() {
        log.info("cut");
    }

    @Before("cut()")
    public void before(JoinPoint joinPoint) {

        //1.获得方法的签名，作为method key
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        AccessLimiter annotation = method.getAnnotation(AccessLimiter.class);
        if(annotation == null) {
            return;
        }
        String key = annotation.methodKey();
        Integer limit = annotation.limit();

        //如果没有设置methodkey，从调用方法签名生成一个key
        if(StringUtils.isEmpty(key)) {
            Class<?>[] parameterTypes = method.getParameterTypes();
            key = method.getName();
            if(parameterTypes != null) {
                String types = Arrays.stream(parameterTypes).map(Class::getName)
                        .collect(Collectors.joining(","));
                log.info("param types: " + types);
                key += '#' + types;
            }
        }

        //step 1:request Lua script
        boolean acquired = stringRedisTemplate.execute(
                rateLimitLua,        //Lua script 的真身
                Lists.newArrayList(key), //Lua脚本中的key列表
                limit.toString()
        );

        if(!acquired) {
            log.error("Your access is blocked key={}", key);
            throw new RuntimeException("Your access is blocked");
        }
    }
}
